<template>
  <div class="process-route">
    <div class="action-bar">
      <el-button type="primary" plain @click="openFlowDesign" :disabled="selectedRows.length !== 1">
        流程设计
      </el-button>
      <div class="right-actions">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
        <el-button type="text" class="icon-btn" @click="toggleSearch" title="显示/隐藏查询">
          <el-icon><Search /></el-icon>
        </el-button>
        <el-button type="text" class="icon-btn" title="刷新" @click="loadData">
          <el-icon><Refresh /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 查询条件 -->
    <div class="search-bar" v-show="showSearch">
      <el-form :inline="true" :model="queryForm">
        <el-form-item label="名称:">
          <el-input v-model="queryForm.processrouteName" placeholder="请输入名称" style="width: 360px" />
        </el-form-item>
        <el-form-item label="状态:">
          <el-select v-model="queryForm.processrouteState" placeholder="请选择状态" style="width: 240px" clearable>
            <el-option :value="true" label="已发布" />
            <el-option :value="false" label="未发布" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-container">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="name" label="名称" min-width="160" />
        <el-table-column label="预览图" width="140">
          <template #default="scope">
            <div class="preview-box" v-if="hasRealImage(scope.row.preview)" @click="openPreview(scope.row.preview)">
              <el-image
                :src="scope.row.preview"
                fit="cover"
                class="preview-img"
                loading="lazy"
                @load="handleImageLoad(scope.row)"
                @error="handleImageError(scope.row)"
              >
                <template #loading>
                  <div class="image-slot">
                    <span>加载中...</span>
                  </div>
                </template>
                <template #error>
                  <div class="image-slot">
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="preview-mask">
                <span class="eye">👁</span>
                <span>预览</span>
              </div>
            </div>
            <div v-else class="no-image-placeholder">
              <span>暂无预览图</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag size="small">{{ scope.row.type }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="110">
          <template #default="scope">
            <el-tag type="success" size="small" v-if="scope.row.status==='已发布'">已发布</el-tag>
            <el-tag type="danger" size="small" v-else>未发布</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="160" />
        <el-table-column prop="creator" label="创建人" width="140" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <!-- <el-button type="primary" link>设计</el-button> -->
            <!-- <el-button type="primary" link>作业指导书</el-button> -->
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
            <el-dropdown trigger="click" @command="handleMoreAction">
              <el-button type="primary" link>
                更多<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    :command="{action: 'publish', row: scope.row}"
                    :disabled="scope.row.status === '已发布'"
                  >
                    发布
                  </el-dropdown-item>
                  <el-dropdown-item 
                    :command="{action: 'unpublish', row: scope.row}"
                    :disabled="scope.row.status === '未发布'"
                  >
                    取消发布
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pagination-container">
      <span>共{{ total }} 条数据</span>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
      />
      <div class="page-size">
        <span>{{ pageSize }} 条/页</span>
      </div>
    </div>
    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" width="80%" title="工艺路线预览" align-center>
      <div class="preview-large">
        <el-image :src="previewSrc" fit="contain" :preview-src-list="[previewSrc]" :initial-index="0"/>
      </div>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addDialogVisible" width="500px" title="新增工艺路线" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="名称" prop="processrouteName">
          <el-input v-model="addForm.processrouteName" placeholder="请输入工艺路线名称" />
        </el-form-item>
        <el-form-item label="类型" prop="processrouteType">
          <el-select v-model="addForm.processrouteType" placeholder="请选择工艺类型" style="width: 100%">
            <el-option label="维修" value="维修" />
            <el-option label="一般" value="一般" />
            <el-option label="测试" value="测试" />
            <el-option label="编营" value="编营" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="processrouteDescription">
          <el-input 
            v-model="addForm.processrouteDescription" 
            type="textarea" 
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitAdd" :loading="addLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="editDialogVisible" width="500px" title="编辑工艺路线" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="名称" prop="processrouteName">
          <el-input v-model="editForm.processrouteName" placeholder="请输入工艺路线名称" />
        </el-form-item>
        <el-form-item label="类型" prop="processrouteType">
          <el-select v-model="editForm.processrouteType" placeholder="请选择工艺类型" style="width: 100%">
            <el-option label="维修" value="维修" />
            <el-option label="一般" value="一般" />
            <el-option label="测试" value="测试" />
            <el-option label="编营" value="编营" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="processrouteDescription">
          <el-input 
            v-model="editForm.processrouteDescription" 
            type="textarea" 
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitEdit" :loading="editLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 流程设计对话框 -->
    <el-dialog 
      v-model="flowDesignVisible" 
      title="流程设计1" 
      width="95%" 
      top="2vh"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      destroy-on-close
    >
      <LogicflowCustom />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="flowDesignVisible = false">关闭</el-button>


          <el-button type="primary" @click="handleSaveFlow">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Search, Refresh, ArrowDown } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs, extractFileName, getImageUrl } from '@/Http/http'
import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'
// @ts-ignore
import LogicflowCustom from './logicflowCustom.vue'

interface RouteRow {
  id: number
  name: string
  type: string
  status: '已发布' | '未发布'
  description: string
  creator: string
  createTime: string
  updateTime: string
  preview: string
}

const tableData = ref<RouteRow[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const previewVisible = ref(false)
const previewSrc = ref('')
const showSearch = ref(false)
const queryForm = ref<{ processrouteName: string; processrouteState: boolean | undefined }>({
  processrouteName: '',
  processrouteState: undefined
})
const selectedRows = ref<RouteRow[]>([])

// 流程设计相关变量
const flowDesignVisible = ref(false)

// 新增相关变量
const addDialogVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref()
const addForm = ref({
  processrouteName: '',
  processrouteType: '',
  processrouteDescription: ''
})

// 编辑相关变量
const editDialogVisible = ref(false)
const editLoading = ref(false)
const editFormRef = ref()
const editForm = ref({
  id: 0,
  processrouteName: '',
  processrouteType: '',
  processrouteDescription: '',
  processrouteState: false,
  processrouteUpdateTime: ''
})


// 表单验证规则
const addFormRules = {
  processrouteName: [
    { required: true, message: '请输入工艺路线名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  processrouteType: [
    { required: true, message: '请选择工艺类型', trigger: 'change' }
  ],
  processrouteDescription: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

const editFormRules = {
  processrouteName: [
    { required: true, message: '请输入工艺路线名称', trigger: 'blur' },
    { min: 1, max: 50, message: '名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  processrouteType: [
    { required: true, message: '请选择工艺类型', trigger: 'change' }
  ],
  processrouteDescription: [
    { max: 200, message: '描述不能超过200个字符', trigger: 'blur' }
  ]
}

onMounted(() => {
  loadData()
})

const loadData = async () => {
  try {
    // console.log('📡 开始加载数据...')
    const res = await APIs.get('/api/Processroute/ShowProcessroute', {
      params: {
        PageIndex: currentPage.value,
        PageSize: pageSize.value,
        ProcessrouteName: queryForm.value.processrouteName || undefined,
        ProcessrouteState: typeof queryForm.value.processrouteState === 'boolean' ? queryForm.value.processrouteState : undefined,
      }
    })
    // console.log('📡 API响应状态:', res.status)
    // console.log('📡 API响应数据结构:', {
    //   isArray: Array.isArray(res.data),
    //   hasData: !!res.data?.data,
    //   dataType: typeof res.data,
    //   dataKeys: res.data ? Object.keys(res.data) : []
    // })
    
    const list = Array.isArray(res.data) ? res.data : (res.data?.data ?? [])
    total.value = (res.data?.totalCount ?? res.data?.total ?? list.length) || list.length

    // console.log('🔍 数据列表长度:', list.length)
    // console.log('🔍 第一条完整数据:', list[0]) // 调试：查看第一条数据的结构
    
    // 检查所有记录的图片字段
    list.forEach((item: any, index: number) => {
      // console.log(`🔍 记录${index + 1}的图片字段:`, {
      //   id: item.id || item.processrouteId,
      //   name: item.processrouteName || item.name,
      //   processroutePreview: item.processroutePreview,
      //   image: item.image,
      //   Image: item.Image,
      //   所有字段: Object.keys(item)
      // })
    })

    const startIndex = (currentPage.value - 1) * pageSize.value
    tableData.value = list.map((item: any, idx: number) => ({
      id: item.id ?? item.processrouteId ?? startIndex + idx + 1,
      name: item.processrouteName ?? item.name ?? '',
      type: item.processrouteType ?? item.type ?? '',
      status: (item.processrouteState ?? item.status) ? '已发布' : '未发布',
      description: item.processrouteDescription ?? item.description ?? '',
      creator: item.processrouteCreatorName ?? item.creator ?? '',
      createTime: item.processrouteCreatorTime ?? item.createTime ?? '',
      updateTime: item.processrouteUpdateTime ?? item.updateTime ?? '',
      preview: (() => {
        const imageName = item.processroutePreview || item.image || item.Image || ''
        // console.log(`🔍 行${idx + 1}原始数据:`, {
        //   processroutePreview: item.processroutePreview,
        //   image: item.image,
        //   Image: item.Image,
        //   原始值: imageName,
        //   类型: typeof imageName
        // })
        
        // 如果原始值为空，直接返回空字符串
        if (!imageName || imageName.trim() === '') {
          // console.log(`❌ 行${idx + 1}无图片数据`)
          return ''
        }
        
        let fullImageUrl = ''
        
        // 如果已经是完整URL，直接使用
        if (imageName.startsWith('http://') || imageName.startsWith('https://')) {
          fullImageUrl = imageName
          // console.log(`✅ 行${idx + 1}已是完整URL:`, fullImageUrl)
        } 
        // 如果是相对路径（如 uploads/images/xxx.png 或 Img/xxx.png），需要拼接baseURL
        else if (imageName.includes('/')) {
          const baseURL = APIs.defaults.baseURL || '';
          fullImageUrl = `${baseURL}/${imageName}`
          // console.log(`🔧 行${idx + 1}拼接相对路径:`, fullImageUrl)
        }
        // 如果只是文件名，使用getImageUrl处理
        else {
          fullImageUrl = getImageUrl(imageName)
          // console.log(`🔧 行${idx + 1}处理文件名:`, fullImageUrl)
        }
        
        // console.log(`🖼️ 行${idx + 1}最终URL:`, fullImageUrl)
        return fullImageUrl
      })()
    }))
  } catch (error) {
    // console.error('加载工序路线数据失败:', error)
  }
}

const handleAdd = () => {
  addDialogVisible.value = true
  // 重置表单
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  addForm.value = {
    processrouteName: '',
    processrouteType: '',
    processrouteDescription: ''
  }
}

const handleSubmitAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    // 表单验证
    await addFormRef.value.validate()
    
    addLoading.value = true
    
    // 调用新增API
    await APIs.post('/api/Processroute/AddProcessroute', {
      processrouteName: addForm.value.processrouteName,
      processrouteType: addForm.value.processrouteType,
      processrouteDescription: addForm.value.processrouteDescription
    })
    
    ElMessage.success('新增成功')
    addDialogVisible.value = false
    
    // 刷新数据
    loadData()
  } catch (error) {
    // console.error('新增失败:', error)
    ElMessage.error('新增失败')
  } finally {
    addLoading.value = false
  }
}

const handleEdit = (row: RouteRow) => {
  // 反填数据
  editForm.value = {
    id: row.id,
    processrouteName: row.name,
    processrouteType: row.type,
    processrouteDescription: row.description,
    processrouteState: row.status === '已发布',
    processrouteUpdateTime: new Date().toISOString()
  }
  
  editDialogVisible.value = true
  
  // 清除表单验证
  if (editFormRef.value) {
    editFormRef.value.clearValidate()
  }
}

const handleSubmitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    // 表单验证
    await editFormRef.value.validate()
    
    editLoading.value = true
    
    // 调用编辑API
    await APIs.post('/api/Processroute/UpdateProcessroute', {
      id: editForm.value.id,
      processrouteName: editForm.value.processrouteName,
      processrouteType: editForm.value.processrouteType,
      processrouteState: editForm.value.processrouteState,
      processrouteDescription: editForm.value.processrouteDescription,
      processrouteUpdateTime: editForm.value.processrouteUpdateTime
    })
    
    ElMessage.success('编辑成功')
    editDialogVisible.value = false
    
    // 刷新数据
    loadData()
  } catch (error) {
    // console.error('编辑失败:', error)
    ElMessage.error('编辑失败')
  } finally {
    editLoading.value = false
  }
}

const handleDelete = async (row: RouteRow) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除工艺路线 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )
    
    // 调用删除API
    await APIs.post('/api/Processroute/DeleteProcessroute', {
      id: row.id
    })
    
    ElMessage.success('删除成功')
    
    // 刷新数据
    loadData()
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return
    }
    // console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

const openFlowDesign = async () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请选择一条记录进行流程设计')
    return
  }
  
  const selectedRow = selectedRows.value[0]
  currentSelectedId = selectedRow.id  // 存储当前选中行的ID
  console.log('当前选中的工艺路线:', selectedRow)
  console.log('存储的ID:', currentSelectedId)
  
  // 尝试加载已保存的流程设计数据
  await loadExistingFlowData(currentSelectedId)
  
  flowDesignVisible.value = true
}




var currentSelectedId = 0;  // 当前选中行的ID
var existingFlowData = null;  // 存储已有的流程数据

// 加载已存在的流程设计数据
const loadExistingFlowData = async (id: number) => {
  try {
    console.log('🔍 开始加载流程设计数据, ID:', id)
    
    // 调用API获取流程设计数据 - 先尝试通过ID过滤
    let response = await APIs.get('/api/Processroute/ShowProcessroute', {
      params: { 
        PageIndex: 1,
        PageSize: 1000, // 增大页面大小以确保能找到目标记录
        Id: id  // 尝试通过ID过滤
      }
    })
    
    console.log('📡 API响应:', response.data)
    
    // 检查响应数据结构 - ShowProcessroute返回数组
    const dataList = Array.isArray(response.data) ? response.data : (response.data?.data ?? [])
    
    // 查找匹配的记录
    let targetRecord = dataList.find((item: any) => (item.id || item.processrouteId) === id)
    console.log('🎯 找到的目标记录:', targetRecord)
    
    // 如果没有找到记录，尝试获取所有数据再查找
    if (!targetRecord && dataList.length === 0) {
      console.log('🔄 没有找到记录，尝试获取所有数据...')
      response = await APIs.get('/api/Processroute/ShowProcessroute', {
        params: { 
          PageIndex: 1,
          PageSize: 1000
        }
      })
      
      const allDataList = Array.isArray(response.data) ? response.data : (response.data?.data ?? [])
      targetRecord = allDataList.find((item: any) => (item.id || item.processrouteId) === id)
      console.log('🔍 在所有数据中找到的记录:', targetRecord)
    }
    
    if (targetRecord && (targetRecord.nodes || targetRecord.processrouteNodes)) {
      try {
        // 尝试解析JSON数据 - 使用正确的字段名
        const nodesData = targetRecord.nodes || targetRecord.processrouteNodes
        const flowData = typeof nodesData === 'string' ? JSON.parse(nodesData) : nodesData
        existingFlowData = flowData
        
        console.log('✅ 成功加载流程设计数据:', flowData)
        console.log('🖼️ 关联的图片:', targetRecord.image || targetRecord.processrouteImage || targetRecord.processroutePreview || '无图片')
        
        // 设置全局变量供LogicFlow组件访问
        ;(window as any).existingFlowData = flowData
        
        // 如果有图片，也保存图片信息
        const imageField = targetRecord.image || targetRecord.processrouteImage || targetRecord.processroutePreview
        if (imageField) {
          const fullImageUrl = getImageUrl(imageField)
          // 设置全局变量供保存时使用
          ;(window as any).flowImageUrl = fullImageUrl
          console.log('🖼️ 设置图片URL:', fullImageUrl)
        }
        
        ElMessage.success('成功加载已保存的流程设计')
      } catch (parseError) {
        console.error('❌ 解析流程数据失败:', parseError)
        console.log('🔍 原始nodes数据:', targetRecord.nodes || targetRecord.processrouteNodes)
        existingFlowData = null
        ElMessage.warning('流程数据格式异常，将创建新的流程')
      }
    } else {
      if (!targetRecord) {
        console.log('⚠️ 未找到ID为', id, '的工艺路线记录')
      } else {
        console.log('ℹ️ 找到记录但没有流程设计数据，记录详情:', targetRecord)
        console.log('🔍 检查的字段:', {
          nodes: targetRecord.nodes,
          processrouteNodes: targetRecord.processrouteNodes,
          所有字段: Object.keys(targetRecord)
        })
      }
      existingFlowData = null
      // 清除全局变量
      ;(window as any).existingFlowData = null
      ;(window as any).flowImageUrl = null
    }
  } catch (error) {
    console.error('❌ 加载流程设计数据失败:', error)
    existingFlowData = null
    // 清除全局变量
    ;(window as any).existingFlowData = null
    ;(window as any).flowImageUrl = null
    // 不显示错误消息，因为可能是新建的工艺路线
  }
}

// 保存流程设计
const handleSaveFlow = async () => {
  // console.log('🚀 handleSaveFlow 函数被调用')
  // console.log('🔍 currentSelectedId:', currentSelectedId)
  
  if (!currentSelectedId) {
    // console.error('❌ 没有选中的记录ID')
    ElMessage.warning('没有选中的记录ID')
    return
  }
  
  try {
    // 等待LogicFlow完全加载
    ElMessage.info('正在获取流程设计数据...')
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 通过全局查找LogicFlow实例
    let lfInstance = null
    
    // 查找所有可能包含LogicFlow的元素
    const possibleSelectors = [
      '.flowCanvas .container',
      '.flowCanvas',
      '.container',
      '[class*="container"]'
    ]
    
    for (let selector of possibleSelectors) {
      const elements = document.querySelectorAll(selector)
      for (let element of elements) {
        const el = element as any
        
        // 尝试多种Vue实例获取方式
        const vueInstances = [
          el.__vue_app__?.ctx,
          el.__vueParentComponent?.ctx,
          el._vnode?.ctx,
          el.__vue__
        ]
        
        for (let ctx of vueInstances) {
          if (ctx?.lf && typeof ctx.lf.getGraphRawData === 'function') {
            lfInstance = ctx.lf
            // console.log('✅ 找到LogicFlow实例:', selector)
            break
          }
        }
        
        if (lfInstance) break
      }
      if (lfInstance) break
    }
    
    // 如果还是没找到，尝试通过window对象查找
    if (!lfInstance && (window as any).lf) {
      lfInstance = (window as any).lf
      // console.log('✅ 通过window对象找到LogicFlow实例')
    }
    
    if (!lfInstance) {
      ElMessage.error('无法获取LogicFlow实例')
      // console.error('调试信息: 请在控制台执行以下代码手动获取JSON:')
      // console.error('const container = document.querySelector(".flowCanvas .container"); console.log(JSON.stringify(container.__vue_app__.ctx.lf.getGraphRawData()));')
      return
    }
    
    // 获取JSON数据
    const jsonData = JSON.stringify(lfInstance.getGraphRawData())
    
    // console.log('准备保存的数据:')
    // console.log('- 记录ID:', currentSelectedId)
    // console.log('- JSON长度:', jsonData.length)
    // console.log('- JSON数据:', jsonData)
    
    // 获取上传的图片地址
    const fullImageUrl = (window as any).flowImageUrl || null
    // console.log('🖼️ 图片上传状态检查:')
    // console.log('  - window.flowImageUrl存在:', !!(window as any).flowImageUrl)
    // console.log('  - 完整图片地址:', fullImageUrl || '未上传图片')
    // console.log('  - 图片地址类型:', typeof fullImageUrl)
    // console.log('  - 图片地址长度:', fullImageUrl?.length || 0)
    
    // 检查是否有图片上传
    if (!fullImageUrl) {
      // console.warn('⚠️ 警告: 没有检测到上传的图片！')
      // console.log('💡 提示: 请先点击右下角的图片按钮上传流程图截图，然后再保存')
      ElMessage.warning('图片上传暂时不可用，将只保存流程数据')
      // 临时允许不上传图片也能保存
      // return
    }
    
    // 从完整URL中提取文件名
    // console.log('🧪 测试 extractFileName 函数:')
    // console.log('  - 输入URL:', fullImageUrl)
    // console.log('  - 函数是否存在:', typeof extractFileName)
    
    let imageFileName = ''
    if (fullImageUrl) {
      imageFileName = extractFileName(fullImageUrl)
      // console.log('  - 输出结果:', imageFileName)
      // console.log('  - 是否成功提取:', imageFileName !== fullImageUrl)
      // console.log('  - 提取的文件名:', imageFileName || '无文件名') 
      
      // 验证文件名提取是否正确
      if (!imageFileName || imageFileName === fullImageUrl) {
        // console.error('❌ 文件名提取失败!')
        ElMessage.warning('图片文件名提取失败，将只保存流程数据')
        imageFileName = ''
      }
    }
    
    // 准备保存的数据
    const saveData = {
      Id: currentSelectedId,
      nodes: jsonData,  // JSON字符串
      image: imageFileName || ''   // 如果没有图片，传空字符串
    };
    
    // console.log('🔍 即将发送的保存数据:', saveData);
    // console.log('🔍 image字段的值:', saveData.image);
    // console.log('🔍 image字段的类型:', typeof saveData.image);
    
    // 调用API保存流程设计
    // console.log('📤 开始调用保存API...')
    // console.log('📤 请求URL:', '/api/Processroute/Updateimagenodes')
    // console.log('📤 请求数据:', JSON.stringify(saveData, null, 2))
    
    const response = await APIs.post('/api/Processroute/Updateimagenodes', saveData)
    // console.log('📥 API响应状态:', response.status)
    // console.log('📥 API响应数据:', response.data)
    // console.log('📥 API响应完整:', response)
    
    ElMessage.success('流程设计保存成功')
    // console.log('✅ 保存成功 - ID:', currentSelectedId, 'JSON长度:', jsonData.length, '图片文件名:', imageFileName)
    
    // 更新表格中对应行的预览图
    if (fullImageUrl && currentSelectedId) {
      const rowIndex = tableData.value.findIndex(row => row.id === currentSelectedId)
      if (rowIndex !== -1) {
        tableData.value[rowIndex].preview = fullImageUrl  // 表格显示用完整URL
        // console.log('✅ 已更新表格预览图:', fullImageUrl)
      }
    }
    
    // 关闭对话框
    flowDesignVisible.value = false
    
    // 刷新页面数据
    await loadData()
    
  } catch (error) {
    // console.error('❌ 保存失败:', error)
    ElMessage.error('保存流程设计失败')
  }
}






const handleExport = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的数据')
    return
  }

  try {
    // 准备导出数据
    const exportData = selectedRows.value.map((row, index) => ({
      '序号': index + 1,
      '名称': row.name,
      '类型': row.type,
      '状态': row.status,
      '描述': row.description,
      '创建人': row.creator,
      '创建时间': row.createTime,
      '更新时间': row.updateTime
    }))

    // 创建工作簿
    const worksheet = (XLSX.utils as any).json_to_sheet(exportData)
    const workbook = (XLSX.utils as any).book_new()
    ;(XLSX.utils as any).book_append_sheet(workbook, worksheet, '工艺路线')

    // 设置列宽
    const colWidths = [
      { wch: 8 },  // 序号
      { wch: 20 }, // 名称
      { wch: 12 }, // 类型
      { wch: 12 }, // 状态
      { wch: 30 }, // 描述
      { wch: 12 }, // 创建人
      { wch: 20 }, // 创建时间
      { wch: 20 }  // 更新时间
    ]
    worksheet['!cols'] = colWidths

    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'buffer' })
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    
    // 生成文件名（包含当前时间）
    const now = new Date()
    const timestamp = now.getFullYear() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + '_' +
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0') + 
      String(now.getSeconds()).padStart(2, '0')
    
    const filename = `工艺路线_${timestamp}.xlsx`
    
    // 下载文件
    saveAs(data, filename)
    
    ElMessage.success(`成功导出 ${selectedRows.value.length} 条数据`)
    // console.log('导出数据:', exportData)
  } catch (error) {
    // console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  }
}
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadData()
}
const toggleSearch = () => {
  showSearch.value = !showSearch.value
}
const handleSelectionChange = (rows: RouteRow[]) => {
  selectedRows.value = rows
}
const handleQuery = () => {
  currentPage.value = 1
  loadData()
}
const handleReset = () => {
  queryForm.value.processrouteName = ''
  queryForm.value.processrouteState = undefined
  currentPage.value = 1
  loadData()
}
// 判断是否有真实的图片（不是占位图或空值）
const hasRealImage = (imageUrl: string) => {
  return imageUrl && 
         imageUrl.trim() !== '' && 
         !imageUrl.includes('data:image/svg+xml') && // 排除SVG占位图
         imageUrl.startsWith('http') // 确保是有效的URL
}

const handleImageLoad = (row: any) => {
  // console.log('✅ 图片加载成功:', row.name, row.preview)
}

const handleImageError = (row: any) => {
  // console.error('❌ 图片加载失败:', {
  //   行名称: row.name,
  //   预览URL: row.preview,
  //   URL长度: row.preview?.length || 0,
  //   URL类型: typeof row.preview
  // })
  
  // 尝试用fetch测试图片URL是否可访问
  if (row.preview && row.preview !== previewThumb && row.preview.trim() !== '') {
    // console.log('🔍 开始测试图片URL可访问性:', row.preview)
    
    fetch(row.preview, { method: 'HEAD', mode: 'cors' })
      .then(response => {
        // console.log('📡 图片URL访问结果:', {
        //   状态码: response.status,
        //   状态文本: response.statusText,
        //   响应头: Object.fromEntries(response.headers.entries())
        // })
        
        if (response.ok) {
          // console.log('✅ 图片URL可访问，但el-image加载失败 - 可能是CORS问题')
        } else {
          // console.error('❌ 图片URL不可访问')
        }
      })
      .catch(error => {
        // console.error('❌ 图片URL访问出错:', {
        //   错误信息: error.message,
        //   错误类型: error.name,
        //   完整错误: error
        // })
      })
  } else {
    // console.log('⚠️ 图片URL为空或无效，跳过测试')
  }
}

const openPreview = (src: string) => {
  previewSrc.value = src || previewLarge
  previewVisible.value = true
}

const handleMoreAction = async (command: { action: string, row: RouteRow }) => {
  const { action, row } = command
  
  try {
    if (action === 'publish') {
      // 发布操作 - 设置状态为true
      await APIs.post('/api/Processroute/UpdateStateProcessroute', {
        id: row.id
      })
      ElMessage.success('发布成功')
    } else if (action === 'unpublish') {
      // 取消发布操作 - 设置状态为false
      await APIs.post('/api/Processroute/UpdateStateProcessrouteTow', {
        id: row.id
      })
      ElMessage.success('取消发布成功')
    }
    // 刷新数据
    loadData()
  } catch (error) {
    // console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 简单的SVG占位图（缩略图/大图一致，这里提供两个尺寸数据URI）
const previewThumb =
  'data:image/svg+xml;utf8,' +
  encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" width="200" height="120">
      <rect width="100%" height="100%" fill="#f5f7fa"/>
      <g stroke="#409eff" stroke-width="2" fill="none">
        <rect x="20" y="10" width="60" height="24" rx="12"/>
        <rect x="20" y="50" width="120" height="28" rx="4"/>
        <rect x="20" y="90" width="80" height="24" rx="4"/>
      </g>
      <g stroke="#67C23A" stroke-width="2">
        <path d="M50 34 v10"/>
        <path d="M80 64 h20"/>
        <path d="M60 114 h60"/>
      </g>
    </svg>`
  )

const previewLarge = previewThumb
</script>


<style scoped>
.process-route {
  padding: 20px;
}
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}
.right-actions { display: flex; gap: 10px; }
.table-container { background: #fff; border-radius: 8px; padding: 0; }
.preview-box { position: relative; width: 100px; height: 60px; cursor: pointer; }
.preview-img { width: 100%; height: 100%; border-radius: 4px; border: 1px solid #ebeef5; }
.preview-mask {
  position: absolute; inset: 0; background: rgba(0,0,0,0.45); color: #fff;
  display: none; align-items: center; justify-content: center; gap: 6px; border-radius: 4px;
  font-size: 12px;
}
.preview-box:hover .preview-mask { display: flex; }
.eye { font-size: 14px; }
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  padding: 12px 16px;
  margin-top: 12px;
  border-radius: 8px;
}
.page-size { color: #909399; }
.search-bar { background: #fff; padding: 12px 16px; border-radius: 8px; margin-bottom: 12px; }
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 12px;
  border-radius: 4px;
}
.no-image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100px;
  height: 60px;
  background: #fafafa;
  color: #c0c4cc;
  font-size: 12px;
  border-radius: 4px;
  border: 1px dashed #e4e7ed;
}
</style>


